package com.news.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.news.dao.News_CategoryDao;
import com.news.dao.News_DetailDao;
import com.news.entity.News_Category;
import com.news.entity.News_Detail;

/**
 * Servlet implementation class Update
 */
public class Update extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Update() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int id=Integer.parseInt(request.getParameter("id"));
		ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
		News_DetailDao news_DetailDao =(News_DetailDao) context.getBean("news_DetailDao");
		News_CategoryDao news_CategoryDao=(News_CategoryDao) context.getBean("news_CategoryDao");
		List<News_Category> categories=news_CategoryDao.getAll();
		News_Detail news_Detail =news_DetailDao.getNews_DetailById(id);
		request.setAttribute("categories", categories);
		request.setAttribute("detail", news_Detail);
		request.getRequestDispatcher("update.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
		News_DetailDao news_DetailDao =(News_DetailDao) context.getBean("news_DetailDao");
		News_CategoryDao news_CategoryDao=(News_CategoryDao) context.getBean("news_CategoryDao");
		News_Detail detail =new News_Detail();
		detail.setTitle(request.getParameter("title"));
		detail.setAuthor(request.getParameter("author"));
		detail.setCreatedate(new Date());
		int id=Integer.parseInt(request.getParameter("classify"));
		detail.setNews_Category(news_CategoryDao.getNews_CategoryById(id));
		detail.setSummary(request.getParameter("abstract"));
		detail.setId(Integer.parseInt(request.getParameter("did")));
		news_DetailDao.updateNews_Detail(detail);
		response.sendRedirect("Initialize");
	}

}
